﻿using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Elentok.Common.Wpf.Services
{
  /// <summary>
  /// Defines the menu service
  /// </summary>
  public interface IMenuService
  {
    /// <summary>
    /// Registers the name "<paramref name="menuName"/>" as a menu.
    /// (returns an observable collection of items in that menu
    /// that updates whenever commands are registered with that menu)
    /// </summary>
    /// <param name="menuName"></param>
    /// <returns></returns>
    ReadOnlyObservableCollection<object> RegisterMenu(string menuName);

    /// <summary>
    /// Adds a menu item into a menu
    /// </summary>
    /// <param name="menuName"></param>
    /// <param name="menuItem"></param>
    void RegisterMenuItem(string menuName, object menuItem);
  }

  /// <summary>
  /// The default implementation of <see cref="IMenuService"/>
  /// </summary>
  public class MenuService : IMenuService
  {
    private Dictionary<string, ObservableCollection<object>> menus = new Dictionary<string, ObservableCollection<object>>();

    private ObservableCollection<object> GetMenuItems(string menuName)
    {
      ObservableCollection<object> commands;
      if (this.menus.TryGetValue(menuName, out commands))
        return commands;

      commands = new ObservableCollection<object>();
      this.menus.Add(menuName, commands);
      return commands;
    }

    /// <summary>
    /// Registers the name "<paramref name="menuName"/>" as a menu.
    /// (returns an observable collection of items in that menu
    /// that updates whenever commands are registered with that menu)
    /// </summary>
    /// <param name="menuName"></param>
    /// <returns></returns>
    public ReadOnlyObservableCollection<object> RegisterMenu(string menuName)
    {
      return new ReadOnlyObservableCollection<object>(GetMenuItems(menuName));
    }

    /// <summary>
    /// Adds a menu item into a menu
    /// </summary>
    /// <param name="menuName"></param>
    /// <param name="menuItem"></param>
    public void RegisterMenuItem(string menuName, object menuItem)
    {
      GetMenuItems(menuName).Add(menuItem);
    }
  }
}
